package me.gavin.net

import com.google.gson.Gson
import me.gavin.util.CacheHelper
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

val okhttpClient: OkHttpClient by lazy {
    OkHttpClient.Builder()
        .connectTimeout(15, TimeUnit.SECONDS)
        .readTimeout(15, TimeUnit.SECONDS)
        .writeTimeout(15, TimeUnit.SECONDS)
//        .addInterceptor(get<HeaderInterceptor>())
        .addInterceptor(OKHttpCacheInterceptor())
        .addNetworkInterceptor(OKHttpCacheNetworkInterceptor())
//        .addInterceptor(HttpLoggingInterceptor { it.log(tag = "OkHttp") }
//            .setLevel(HttpLoggingInterceptor.Level.BODY))
        .cache(Cache(File(CacheHelper.cacheDir, "responses"), 50 * 1024 * 1024))
        .build()
}

val retrofit: Retrofit by lazy {
    Retrofit.Builder()
        .baseUrl("https://api.gavin.com/")
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
//        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .client(okhttpClient)
        .build()
}

val gson by lazy { Gson() }